package com.yami.shop.im.socket;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.model.User;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.Json;
import com.yami.shop.im.bean.ImMsgBizUserHistory;
import com.yami.shop.im.bo.ShopSessionInfo;
import com.yami.shop.im.bo.UserSessionInfo;
import com.yami.shop.im.constants.MsgCode;
import com.yami.shop.im.hanlder.SecurityHandler;
import com.yami.shop.im.param.MessageInfo;
import com.yami.shop.im.service.ImMsgBizUserHistoryService;
import com.yami.shop.im.vo.MsgItem;
import com.yami.shop.security.multishop.model.YamiShopUser;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.service.UserService;
import com.yami.shop.sys.comment.model.ShopEmployee;
import com.yami.shop.sys.comment.service.ShopEmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 商家收到的消息
 * 10,"无法获取用户信息"
 * 11,"账户已在别处登录，请刷新"
 * 12,"对方不在线"
 * 13, "内容格式有误"
 *
 * @author Lzk
 */
@ServerEndpoint("/im/websocket/shop/{token}")
@Component
@Slf4j
public class ShopWebSocketServer {

    /**
     * shopId为key
     */
    public static final ConcurrentHashMap<String, ShopSessionInfo> SHOP_EMPLOYEE_MAP = new ConcurrentHashMap<>(256);

    private static final String USER_PREFIX = "USER_";

    private static final String SHOP_EMPLOYEE_PREFIX = "SHOP_EMPLOYEE_";

    private static final String UNDERLINE = "_";

    private static final String IN_CHARGE = "IN_CHARGE_";

    private static SecurityHandler securityHandler;

    private static ShopDetailService shopDetailService;

    private static ShopEmployeeService shopEmployeeService;

    private static UserService userService;

    private static ImMsgBizUserHistoryService imMsgBizUserHistoryService;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        shopDetailService = applicationContext.getBean(ShopDetailService.class);
        shopEmployeeService = applicationContext.getBean(ShopEmployeeService.class);
        securityHandler = applicationContext.getBean(SecurityHandler.class);
        userService = applicationContext.getBean(UserService.class);
        imMsgBizUserHistoryService = applicationContext.getBean(ImMsgBizUserHistoryService.class);
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws IOException {
        log.info("创建连接");
        YamiShopUser shopUser = securityHandler.getShopUser(token);
        if (shopUser == null) {
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(10, "无法获取用户信息")));
            return;
        }

        // 如果原来就有token
        ShopSessionInfo oldShopSessionInfo = SHOP_EMPLOYEE_MAP.get(SHOP_EMPLOYEE_PREFIX + shopUser.getShopId() + UNDERLINE + shopUser.getEmployeeId());
        if (oldShopSessionInfo != null) {
            // 客户端收到11，关闭ws链接，弹出提示
            if (oldShopSessionInfo.getSession().isOpen()) {
                oldShopSessionInfo.getSession().getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(11, "账户已在别处登录，请刷新")));
                oldShopSessionInfo.getSession().close();
            }
        }

        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(shopUser.getShopId());
        ShopEmployee shopEmployee = shopEmployeeService.getShopEmployeeById(shopUser.getEmployeeId());

        ShopSessionInfo shopSessionInfo = new ShopSessionInfo();
        shopSessionInfo.setShopName(shopDetail.getShopName());
        shopSessionInfo.setPic(shopDetail.getShopLogo());
        shopSessionInfo.setShopId(shopDetail.getShopId());
        shopSessionInfo.setEmployeeId(shopEmployee.getEmployeeId());
        shopSessionInfo.setEmployeeNickname(shopEmployee.getNickname());
        shopSessionInfo.setSession(session);

        SHOP_EMPLOYEE_MAP.put(SHOP_EMPLOYEE_PREFIX + shopUser.getShopId() + UNDERLINE + shopUser.getEmployeeId(), shopSessionInfo);
        session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success()));
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("token") String token) {
        log.info("关闭连接");
        YamiShopUser shopUser = securityHandler.getShopUser(token);
        if (shopUser == null) {
            return;
        }
        SHOP_EMPLOYEE_MAP.remove(SHOP_EMPLOYEE_PREFIX + shopUser.getShopId() + UNDERLINE + shopUser.getEmployeeId());
        /*Set<String> set = UserWebSocketServer.IN_CHARGE_MAP.keySet();
        for (String key : set) {
            if (Objects.equals(UserWebSocketServer.IN_CHARGE_MAP.get(key), shopUser.getEmployeeId())) {
                UserWebSocketServer.IN_CHARGE_MAP.remove(key);
            }
        }*/
    }

    /**
     * 连接错误调用的方法
     */
    @OnError
    public void onError(Session session, @PathParam("token") String token, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
        YamiShopUser shopUser = securityHandler.getShopUser(token);
        if (shopUser == null) {
            return;
        }
        SHOP_EMPLOYEE_MAP.remove(SHOP_EMPLOYEE_PREFIX + shopUser.getShopId() + UNDERLINE + shopUser.getEmployeeId());
        /*Set<String> set = UserWebSocketServer.IN_CHARGE_MAP.keySet();
        for (String key : set) {
            if (Objects.equals(UserWebSocketServer.IN_CHARGE_MAP.get(key), shopUser.getEmployeeId())) {
                UserWebSocketServer.IN_CHARGE_MAP.remove(key);
            }
        }*/
    }

    /**
     * 收到客户端消息后调用的方法，该消息由商家发过来
     *
     * @param sourceMessage 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String sourceMessage, @PathParam("token") String token, Session session) throws IOException {
        // from user info
        YamiShopUser shopUser = securityHandler.getShopUser(token);
        if (Objects.isNull(shopUser)) {
            log.error("无法获取用户信息");
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(10, "无法获取用户信息")));
            return;
        }

        if (StrUtil.isBlank(sourceMessage)) {
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(13, "内容格式有误")));
            return;
        }

        log.info("sourceMessage: " + sourceMessage);

        MessageInfo messageInfo = Json.parseObject(sourceMessage, MessageInfo.class);

        if (Objects.isNull(messageInfo)) {
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(13, "内容格式有误")));
            return;
        }

        // 保持心跳
        if (StrUtil.equals(messageInfo.getContent(), Constant.HEART_BEAT)) {
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(0, "保持心跳")));
            return;
        }

        String userId = messageInfo.getToId();
        User user = userService.getUserByUserId(userId);
        if (Objects.isNull(user)) {
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(14, "参数有误")));
            return;
        }

        sendToUser(messageInfo, shopUser, user, session, userId);
    }

    public void sendToUser(MessageInfo messageInfo, YamiShopUser shopUser, User user, Session session, String userId) throws IOException {
        // 获取消息历史
        if (Objects.nonNull(messageInfo.getHistory()) && Objects.equals(messageInfo.getHistory(), true)) {
            Page<MsgItem> msgItemPage = imMsgBizUserHistoryService.getShopUserHistory(shopUser, messageInfo, user);
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.HISTORY, msgItemPage)));
            return;
        }

        // 标记消息已读
        if (Objects.nonNull(messageInfo.getRead()) && Objects.equals(messageInfo.getRead(), true)) {
            if (Objects.nonNull(messageInfo.getMsgIds()) && !messageInfo.getMsgIds().isEmpty()) {
                List<ImMsgBizUserHistory> imMsgBizUserHistories = imMsgBizUserHistoryService.markShopUserRead(messageInfo, shopUser, userId);
                if (!imMsgBizUserHistories.isEmpty()) {
                    session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success()));
                    UserSessionInfo userSessionInfo = UserWebSocketServer.USER_MAP.get(USER_PREFIX + messageInfo.getToId());
                    if (Objects.nonNull(userSessionInfo)) {
                        userSessionInfo.getSession().getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.READ, messageInfo.getMsgIds())));
                    }
                }
            }
            return;
        }

        Long employeeId = UserWebSocketServer.IN_CHARGE_MAP.get(IN_CHARGE + shopUser.getShopId() + UNDERLINE + messageInfo.getToId());
        if (Objects.nonNull(employeeId)) {
            if (!Objects.equals(employeeId, shopUser.getEmployeeId())) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(15, "不是你负责的客户")));
                return;
            }
        }

        // 获取可转接客服列表
        if (Objects.nonNull(messageInfo.getEmployeeList()) && Objects.equals(messageInfo.getEmployeeList(), true)) {
            Set<String> set = SHOP_EMPLOYEE_MAP.keySet();
            List<ShopSessionInfo> listEmployee = new ArrayList<>();
            for (String key : set) {
                if (key.startsWith(SHOP_EMPLOYEE_PREFIX + shopUser.getShopId() + UNDERLINE)) {
                    if (!Objects.equals(SHOP_EMPLOYEE_PREFIX + shopUser.getShopId() + UNDERLINE + shopUser.getEmployeeId(), key)) {
                        ShopSessionInfo shopSessionInfo = ShopWebSocketServer.SHOP_EMPLOYEE_MAP.get(key);
                        ShopSessionInfo shopSessionInfo2 = new ShopSessionInfo();
                        shopSessionInfo2.setShopName(shopSessionInfo.getShopName());
                        shopSessionInfo2.setPic(shopSessionInfo.getPic());
                        shopSessionInfo2.setShopId(shopSessionInfo.getShopId());
                        shopSessionInfo2.setEmployeeId(shopSessionInfo.getEmployeeId());
                        shopSessionInfo2.setEmployeeNickname(shopSessionInfo.getEmployeeNickname());
                        listEmployee.add(shopSessionInfo2);
                    }
                }
            }
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.EMPLOYEE_ONLINE, listEmployee)));
            return;
        }

        // 转接客服
        if (Objects.nonNull(messageInfo.getChangeTo()) && Objects.equals(messageInfo.getChangeTo(), true)) {
            if (Objects.nonNull(messageInfo.getEmployeeId())) {
                UserSessionInfo userSessionInfo = UserWebSocketServer.USER_MAP.get(USER_PREFIX + messageInfo.getToId());
                ShopSessionInfo shopSessionInfo = SHOP_EMPLOYEE_MAP.get(SHOP_EMPLOYEE_PREFIX + shopUser.getShopId() + UNDERLINE + messageInfo.getEmployeeId());
                if (Objects.nonNull(userSessionInfo) && Objects.nonNull(shopSessionInfo)) {
                    UserWebSocketServer.IN_CHARGE_MAP.put(IN_CHARGE + shopUser.getShopId() + UNDERLINE + userSessionInfo.getUserId(), shopSessionInfo.getEmployeeId());
                    ImMsgBizUserHistory imMsgBizUserHistory = imMsgBizUserHistoryService.saveShopChangeEmployeeReply(shopUser, shopSessionInfo, userSessionInfo);
                    MsgItem msgItem = imMsgBizUserHistoryService.getUserShopMsgItem(shopSessionInfo, userSessionInfo, imMsgBizUserHistory);
                    session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.CHANGE_EMPLOYEE_SUCCESS, msgItem)));
                    userSessionInfo.getSession().getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.CHANGE_EMPLOYEE_SUCCESS, msgItem)));
                    shopSessionInfo.getSession().getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.CHANGE_EMPLOYEE_SUCCESS, msgItem)));
                }
            }
            return;
        }

        // 发送消息
        if (Objects.nonNull(messageInfo.getContent()) && !messageInfo.getContent().isEmpty()) {
            ImMsgBizUserHistory imMsgBizUserHistory = imMsgBizUserHistoryService.saveShopUserHistory(messageInfo, shopUser);
            // 在线的话发送消息，不在线的话留言
            UserSessionInfo userSessionInfo = UserWebSocketServer.USER_MAP.get(USER_PREFIX + messageInfo.getToId());
            if (Objects.nonNull(userSessionInfo)) {
                ShopSessionInfo shopSessionInfo = SHOP_EMPLOYEE_MAP.get(SHOP_EMPLOYEE_PREFIX + shopUser.getShopId() + UNDERLINE + shopUser.getEmployeeId());
                MsgItem msgItem = imMsgBizUserHistoryService.getUserShopMsgItem(shopSessionInfo, userSessionInfo, imMsgBizUserHistory);
                userSessionInfo.getSession().getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(msgItem)));
            }
        }
    }

}
